<template>
  <div class="examination-request">
    <el-row :gutter="20">
      <!-- 左侧检查申请表单 -->
      <el-col :span="12">
        <el-card class="form-card">
          <template #header>
            <div class="card-header">
              <span>检查申请单</span>
              <div class="button-group">
                <el-button type="primary" @click="submitRequest" :loading="loading">提交申请</el-button>
                <el-button @click="previewRequest">预览打印</el-button>
              </div>
            </div>
          </template>

          <el-form
            ref="requestForm"
            :model="formData"
            :rules="rules"
            label-width="100px"
            class="request-form"
          >
            <!-- 患者信息 -->
            <el-descriptions title="患者信息" :column="3" border>
              <el-descriptions-item label="姓名">{{ patientInfo.name }}</el-descriptions-item>
              <el-descriptions-item label="性别">{{ patientInfo.gender === 'M' ? '男' : '女' }}</el-descriptions-item>
              <el-descriptions-item label="年龄">{{ patientInfo.age }}</el-descriptions-item>
              <el-descriptions-item label="科室">{{ patientInfo.department }}</el-descriptions-item>
              <el-descriptions-item label="医生">{{ patientInfo.doctor }}</el-descriptions-item>
              <el-descriptions-item label="就诊时间">{{ formatDateTime(patientInfo.visitTime) }}</el-descriptions-item>
            </el-descriptions>

            <!-- 检查信息 -->
            <el-form-item label="检查类型" prop="examinationType">
              <el-select
                v-model="formData.examinationType"
                placeholder="请选择检查类型"
                class="full-width"
              >
                <el-option label="CT" value="CT" />
                <el-option label="MRI" value="MRI" />
                <el-option label="X光" value="XRAY" />
                <el-option label="B超" value="ULTRASOUND" />
                <el-option label="心电图" value="ECG" />
              </el-select>
            </el-form-item>

            <el-form-item label="检查项目" prop="examinationName">
              <el-select
                v-model="formData.examinationName"
                filterable
                remote
                reserve-keyword
                placeholder="请输入检查项目"
                :remote-method="searchExaminations"
                :loading="searching"
                class="full-width"
              >
                <el-option
                  v-for="item in examinationOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="预约时间" prop="scheduledTime">
              <el-date-picker
                v-model="formData.scheduledTime"
                type="datetime"
                placeholder="选择预约时间"
                format="YYYY-MM-DD HH:mm"
                value-format="YYYY-MM-DD HH:mm:ss"
                :disabled-date="disabledDate"
                :disabled-hours="disabledHours"
                class="full-width"
              />
            </el-form-item>

            <el-form-item label="注意事项" prop="notes">
              <el-input
                v-model="formData.notes"
                type="textarea"
                :rows="3"
                placeholder="请输入注意事项"
              />
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>

      <!-- 右侧申请记录列表 -->
      <el-col :span="12">
        <el-card class="list-card">
          <template #header>
            <div class="card-header">
              <span>申请记录</span>
              <el-button type="primary" @click="refreshList">刷新</el-button>
            </div>
          </template>

          <el-table
            :data="requestList"
            style="width: 100%"
            v-loading="loading"
            :height="tableHeight"
          >
            <el-table-column prop="examinationType" label="检查类型" width="100" />
            <el-table-column prop="examinationName" label="检查项目" min-width="150" />
            <el-table-column prop="scheduledTime" label="预约时间" width="150">
              <template #default="scope">
                {{ formatDateTime(scope.row.scheduledTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.status)">
                  {{ getStatusText(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="150">
              <template #default="scope">
                <el-button
                  link
                  type="primary"
                  @click="viewResult(scope.row)"
                  :disabled="scope.row.status !== 'completed'"
                >
                  查看结果
                </el-button>
                <el-button
                  link
                  type="danger"
                  @click="cancelRequest(scope.row)"
                  :disabled="scope.row.status === 'completed'"
                >
                  取消
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :total="total"
              :page-sizes="[10, 20, 30, 50]"
              layout="total, sizes, prev, pager, next"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 结果查看对话框 -->
    <el-dialog
      v-model="resultDialogVisible"
      title="检查结果"
      width="60%"
    >
      <div v-if="selectedRequest">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="检查类型">{{ selectedRequest.examinationType }}</el-descriptions-item>
          <el-descriptions-item label="检查项目">{{ selectedRequest.examinationName }}</el-descriptions-item>
          <el-descriptions-item label="检查时间">{{ formatDateTime(selectedRequest.completedTime) }}</el-descriptions-item>
          <el-descriptions-item label="检查医生">{{ selectedRequest.doctorName }}</el-descriptions-item>
        </el-descriptions>
        <div class="result-content">
          <h4>检查结果：</h4>
          <div v-html="selectedRequest.result"></div>
        </div>
        <div class="result-images" v-if="selectedRequest.images && selectedRequest.images.length">
          <h4>检查图片：</h4>
          <el-image
            v-for="(image, index) in selectedRequest.images"
            :key="index"
            :src="image"
            :preview-src-list="selectedRequest.images"
            fit="cover"
            class="result-image"
          />
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="printResult">打印结果</el-button>
          <el-button @click="resultDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

// 模拟患者信息
const patientInfo = ref({
  id: 1,
  name: '张三',
  gender: 'M',
  age: 35,
  department: '内科',
  doctor: '李医生',
  visitTime: '2024-04-29T10:00:00Z'
})

// 表单数据
const formData = ref({
  examinationType: '',
  examinationName: '',
  scheduledTime: '',
  notes: ''
})

// 表单验证规则
const rules = ref<FormRules>({
  examinationType: [
    { required: true, message: '请选择检查类型', trigger: 'change' }
  ],
  examinationName: [
    { required: true, message: '请选择检查项目', trigger: 'change' }
  ],
  scheduledTime: [
    { required: true, message: '请选择预约时间', trigger: 'change' }
  ]
})

// 在 script setup 部分的开头添加类型定义
interface ExaminationOption {
  value: string
  label: string
}

interface ExaminationRequest {
  id: number
  examinationType: string
  examinationName: string
  scheduledTime: string
  status: string
  notes: string
  completedTime?: string
  doctorName?: string
  result?: string
  images?: string[]
}

// 修改变量定义
// 检查项目选项
const examinationOptions = ref<ExaminationOption[]>([])
const searching = ref(false)

// 列表数据
const requestList = ref<ExaminationRequest[]>([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const tableHeight = ref('500px')

// 结果查看
const resultDialogVisible = ref(false)
const selectedRequest = ref<ExaminationRequest | null>(null)

// 表单引用
const requestForm = ref<FormInstance>()

// 方法定义
const formatDateTime = (dateStr: string | undefined): string => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    pending: 'warning',
    completed: 'success',
    cancelled: 'info'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    pending: '待检查',
    completed: '已完成',
    cancelled: '已取消'
  }
  return statusMap[status] || '未知'
}

// 搜索检查项目
const searchExaminations = async (query: string) => {
  if (query) {
    searching.value = true
    // 模拟API调用
    setTimeout(() => {
      examinationOptions.value = [
        { value: '胸部CT', label: '胸部CT' },
        { value: '头颅CT', label: '头颅CT' },
        { value: '腹部B超', label: '腹部B超' }
      ].filter(item => item.label.toLowerCase().includes(query.toLowerCase()))
      searching.value = false
    }, 500)
  }
}

// 提交申请
const submitRequest = async () => {
  if (!requestForm.value) return
  
  await requestForm.value.validate((valid) => {
    if (valid) {
      loading.value = true
      // 模拟API调用
      setTimeout(() => {
        ElMessage.success('申请提交成功')
        loading.value = false
        refreshList()
      }, 1000)
    }
  })
}

// 预览打印
const previewRequest = () => {
  // 实现打印预览逻辑
  window.print()
}

// 刷新列表
const refreshList = () => {
  loading.value = true
  // 模拟API调用
  setTimeout(() => {
    requestList.value = [
      {
        id: 1,
        examinationType: 'CT',
        examinationName: '胸部CT',
        scheduledTime: '2024-04-30T14:30:00Z',
        status: 'pending',
        notes: '请空腹检查'
      }
    ]
    total.value = 1
    loading.value = false
  }, 500)
}

// 查看结果
const viewResult = (row: any) => {
  selectedRequest.value = row
  resultDialogVisible.value = true
}

// 取消申请
const cancelRequest = (row: any) => {
  ElMessageBox.confirm(
    '确定要取消该检查申请吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 模拟API调用
    setTimeout(() => {
      ElMessage.success('申请已取消')
      refreshList()
    }, 500)
  })
}

// 打印结果
const printResult = () => {
  window.print()
}

// 日期禁用
const disabledDate = (time: Date) => {
  return time.getTime() < Date.now() - 8.64e7
}

// 时间禁用
const disabledHours = () => {
  return Array.from({ length: 24 }, (_, i) => i).filter(h => h < 8 || h > 17)
}

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  refreshList()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  refreshList()
}

// 生命周期钩子
onMounted(() => {
  refreshList()
})
</script>

<style scoped>
.examination-request {
  padding: 20px;
}

.form-card,
.list-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.button-group {
  display: flex;
  gap: 10px;
}

.request-form {
  margin-top: 20px;
}

/* 添加表格和表单项之间的边距 */
.el-descriptions {
  margin-bottom: 20px;
}

.el-form-item {
  margin-top: 20px;
}

.full-width {
  width: 100%;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.result-content {
  margin: 20px 0;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.result-images {
  margin-top: 20px;
}

.result-image {
  width: 100px;
  height: 100px;
  margin-right: 10px;
  margin-bottom: 10px;
  cursor: pointer;
}

/* 打印样式 */
@media print {
  .el-button,
  .pagination {
    display: none;
  }
}
</style> 